const express = require('express')
const router = express.Router()

// import the entrypted plugin of bctypt
const bcrypt = require('bcrypt')
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const keys = require('../../config/keys')
const passport = require('passport')


const User = require('../../models/User')

/* $router GET /api/users/test
  @desc return the request data of Json
  @access Public
*/
// router.get('/test', (req, res) => {
//   res.json({msg: 'login works'})
// })

/* $router POST /api/users/register
  @desc return the request data of Json
  @access Public
*/
router.post('/register', (req, res) => {
  // query whether the mongodb has the email or not 
  User.findOne({
    email: req.body.email
  }).then(user => {
    if (user) {
      return res.status(400).json('邮箱已被注册!')  
    } else {
       // set avatar
      const avatar = gravatar.url(req.body.email, {
        s: '200',
        r: 'pg',
        d: 'mm'
      })
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        avatar,
        password: req.body.password,
        identity: req.body.identity
      })
      // password encryption
      // hash is the encrypted password
      bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err
          newUser.password = hash
          // save the newUser on the mongodb schema
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err))
        })
      })
    }
  })
})

/* $router POST /api/users/login
  @desc return the request data of Json
  @access Public
*/
router.post('/login', (req, res) => {
  const email = req.body.email
  const password = req.body.password
  // query mongodb
  User.findOne({email})
      .then(user => { 
        if (!user) {
          return res.status(400).json('用户不存在!')
        }
      
      // password match
      bcrypt.compare(password, user.password)
            .then(isMatch => {
              if (isMatch) {
                // jwt.sign('rule','secretname','enpiredtime','arrowfunction')
                const rule = {
                  id: user.id, 
                  name: user.name,
                  avatar: user.avatar,
                  identity: user.identity
                }
                jwt.sign(rule, keys.secretOrKey, {expiresIn: 3600 }, (err, token) => {
                  res.json({
                    success: true,
                    token: 'Bearer ' + token
                  })
                })
                // res.json({msg: 'success'})
              } else {
                return res.status(400).json('密码错误!')
              }
            })
        })
    })

/* $router GET /api/users/current
  @desc return the user information by token
  @access Private
*/
// vertify whether the token is correct or not  by passport 
router.get('/current', passport.authenticate('jwt', {session: false}), (req, res) => {
  // retuen user information
  res.json({
    id: req.user.id,
    name: req.user.name,
    email: req.user.email,
    identity: req.user.identity
  })
})
module.exports = router